<?php


namespace app\common\model\base;

use app\common\model\BaseModel;
use helper\Tree;

class DictClassModel extends BaseModel
{
    protected $table = 'dict_class';

    /**
     * 分类列表
     * @return array
     * @throws \Exception
     */
    public function getList(){
        $list = $this->order('show_order asc')->select()->toArray();
        $treeList = Tree::tree($list,'name'); //转换树型
        return array_values($treeList);
    }

    /**
     * 添加
     * @param $data
     * @return DictClassModel|\think\Model
     * @throws \Exception
     */
    public function add($data){
        if($this->where('code',$data['code'])->find()) exception('该编码已存在');
        return self::create($data);
    }

    /**
     * 编辑
     * @param $data
     * @return DictClassModel|\think\Model
     * @throws \Exception
     */
    public function edit($data){
        $info = $this->where('id',$data['id'])->find();
        if($info['code']!=$data['code']){
            if($this->where('code',$data['code'])->find()) exception('该编码已存在');
            //批量更新字典对应编码
            DictItemModel::where('class_code', $info['code'])->update(['class_code' => $data['code']]);
        }
        return self::update($data);
    }

    /**
     * 删除
     * @param $id
     * @throws \Exception
     */
    public function del($id){
        $info = $this->where('id',$id)->find();
        if($this->where('pid',$id)->find()) exception('存在下级分类，不允许删除');
        if(DictItemModel::where('class_code', $info['code'])->find()) exception('存在对应字典，不允许删除');
        $this->where('id',$id)->delete();
    }

}